<template>
  <div class="layout">
    <Header />
    <div class="container">
      <div class="table-container">
        <div class="info">
          <div class="table-name">
            维护信息列表<span style="float: right"><el-button size="small" type="primary"
                @click="handleAdd">添加模板</el-button></span>
          </div>
          <el-config-provider :locale="zhCn">
            <el-table :data="mapStore.templateTableData" border style="width: 100%" :row-style="tableRowStyle">
              <el-table-column prop="appid" label="项目ID" />
              <el-table-column prop="code" label="Word代码" />
              <el-table-column prop="url" label="请求数据地址" />
              <el-table-column prop="downloadName" label="下载名称" width="200" />
              <el-table-column prop="createTime" label="创建时间" />
              <el-table-column label="维护信息操作" width="140">
                <template #default="scope">
                  <el-button size="small" type="text" @click="handleEdit(scope)">修改</el-button>
                  <el-button size="small" type="text" @click="handleDelete(scope)">删除</el-button>
                </template>
              </el-table-column>
              <el-table-column label="模板操作" width="200">
                <template #default="scope">
                  <el-button size="small" type="text" @click="handleUpload(scope)">{{ scope.row.tmExist ? "更新" : "上传"
                    }}</el-button>
                  <el-button size="small" type="text" @click="handlePreview(scope, 'template')"
                    v-if="scope.row.tmExist">预览</el-button>
                  <el-button size="small" type="text" @click="handleDownload(scope, 'template')"
                    v-if="scope.row.tmExist">下载</el-button>
                </template>
              </el-table-column>
              <el-table-column label="生成操作" width="160">
                <template #default="scope">
                  <el-button size="small" type="text" @click="handlePreview(scope, 'file')"
                    v-if="scope.row.tmExist">预览</el-button>
                  <el-button size="small" type="text" @click="handleDownload(scope, 'file')"
                    v-if="scope.row.tmExist">下载</el-button>
                </template>
              </el-table-column>
            </el-table>

            <div class="space-15"></div>

            <el-pagination size="small" background layout="total, sizes, prev, pager, next"
              :current-page="mapStore.templateTableCurrentPage" :page-size="mapStore.templateTablePageSize"
              :page-sizes="[5, 10]" :total="mapStore.templateTableTotal" @size-change="handleSizeChange"
              @current-change="handleCurrentChange" />
          </el-config-provider>
        </div>
      </div>
    </div>
  </div>

  <DialogForAdd ref="childOfDialogForAdd" />
  <DialogForUpload ref="childOfDialogForUpload" />
</template>

<script setup>
import { ref, onMounted } from "vue";
import zhCn from "element-plus/es/locale/lang/zh-cn";
import { ElMessage, ElMessageBox } from "element-plus";
import axios from "axios";
import Header from "@/components/Header.vue";
import DialogForAdd from "@/DialogForAdd.vue";
import DialogForUpload from "@/DialogForUpload.vue";
import { fetchTemplateData, handleAjaxDelete } from "@/api/get-data.js";
import pinia from "@/store/pinia";
import { useMapStore } from "@/store/map";
const mapStore = useMapStore(pinia);

const childOfDialogForAdd = ref(null);
const childOfDialogForUpload = ref(null);

// 分页大小改变时的回调
const handleSizeChange = (val) => {
  mapStore.templateTablePageSize = val;
  fetchTemplateData(
    mapStore.templateTableCurrentPage,
    mapStore.templateTablePageSize
  );
};

// 当前页改变时的回调
const handleCurrentChange = (val) => {
  mapStore.templateTableCurrentPage = val;
  fetchTemplateData(
    mapStore.templateTableCurrentPage,
    mapStore.templateTablePageSize
  );
};

const tableRowStyle = (row) => {
  return row.rowIndex % 2 === 0
    ? { background: "rgba(14, 95, 255, 0.05)", cursor: "pointer" }
    : { background: "rgba(14, 95, 255, 0.15)", cursor: "pointer" };
};

const handleAdd = () => {
  childOfDialogForAdd.value.dialogOperateName = "add";
  childOfDialogForAdd.value.dialogVisible = true;
};

const handleEdit = (scope) => {
  childOfDialogForAdd.value.dialogOperateName = "edit";
  childOfDialogForAdd.value.dialogVisible = true;
  childOfDialogForAdd.value.ruleForm.downloadName = scope.row.downloadName;
  childOfDialogForAdd.value.ruleForm.code = scope.row.code;
  childOfDialogForAdd.value.ruleForm.appid = scope.row.appid;
  childOfDialogForAdd.value.ruleForm.url = scope.row.url;
  childOfDialogForAdd.value.currentUUID = scope.row.uuid;
};

const handleDelete = (scope) => {
  ElMessageBox.confirm(`确认删除模板【${scope.row.downloadName}】?`, "确认", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      handleAjaxDelete(scope);
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: "已取消",
      });
    });
};

const handleUpload = (scope) => {
  childOfDialogForUpload.value.dialogUploadVisible = true;
  childOfDialogForUpload.value.currentCode = scope.row.code;
};

// word预览时生成data
const generateWordData = async (code) => {
  let handlePreviewRes = await axios
    .post("/WordTool/word/generate/generate", {
      tmCode: code,
      jsonData: { yearMonth: "2024-8" },
    })
    .then((handlePreviewRes) => [null, handlePreviewRes])
    .catch((err) => [err, null]);

  console.log("预览：");
  console.log(handlePreviewRes);

  if (!handlePreviewRes[1]) {
    console.log(handlePreviewRes[1].data.message);
    ElMessage({
      message: handlePreviewRes[1].data.message,
      type: "error",
    });
    return false;
  }

  handlePreviewRes = handlePreviewRes[1];
  console.log(handlePreviewRes.data.data);
  return handlePreviewRes.data.data;
};

const handlePreview = async (scope, type) => {
  if (type === "template") {
    window.open(`/preview_template/${scope.row.code}`, "_blank");
  } else if (type === "file") {
    generateWordData(scope.row.code).then((data) => {
      if (data) {
        console.log("Data received:", data);
        window.open(`/preview/${data}`, "_blank");
      }
    });
  }
};

const handleDownload = (scope, type) => {
  const iframe = document.createElement("iframe");
  iframe.style.display = "none";
  iframe.style.height = 0;

  if (type === "template") {
    iframe.src = `${import.meta.env.VITE_APP_API_HOST}/WordTool/word/template/download?tmCode=${scope.row.code}`;
    document.body.appendChild(iframe);
  } else if (type === "file") {
    generateWordData(scope.row.code).then((data) => {
      if (data) {
        iframe.src = `${import.meta.env.VITE_APP_API_HOST}/WordTool/word/generate/download?generateInfoId=${data}`;
        document.body.appendChild(iframe);
      }
    });
  }

  setTimeout(function () {
    iframe.remove();
  }, 5 * 60 * 1000);
};

onMounted(() => {
  fetchTemplateData(
    mapStore.templateTableCurrentPage,
    mapStore.templateTablePageSize
  );
});
</script>

<style scoped>
.container {
  width: 1440px;
  margin: 0 auto;
  padding: 10px;
  height: 100%;
}

.table-container {
  width: 100%;
  height: 100%;
  overflow-x: auto;
}

.table-name {
  height: 50px;
  line-height: 40px;
  padding-left: 15px;
  background: url("./assets/images/holder.png") no-repeat scroll left center;
  background-size: cover;
  color: #fff;
  font-size: 20px;
}

.el-table {
  /* --el-table-border-color: transparent;
  --el-table-border: none; */
  /* --el-table-border: 1px solid rgba(19, 84, 134, 0.25); */
  --el-table-border-color: rgba(11, 53, 109, 0.25);
  --el-table-border: 1px solid rgba(11, 53, 109, 0.25);
  --el-table-text-color: #bdbdbe;
  --el-table-header-text-color: #bdbdbe;
  /* --el-table-row-hover-bg-color: transparent; */
  --el-table-row-hover-bg-color: rgba(14, 95, 255, 0.25);
  /* --el-table-current-row-bg-color: transparent; */
  --el-table-current-row-bg-color: rgba(19, 84, 134, 0.5);
  /* --el-table-header-bg-color: transparent; */
  --el-table-header-bg-color: rgba(19, 84, 134, 0.5);
  /* --el-table-bg-color: transparent; */
  --el-table-bg-color: rgba(19, 84, 134, 0.25);
  /* --el-table-tr-bg-color: transparent; */
  --el-table-tr-bg-color: rgba(19, 84, 134, 0.25);
  --el-table-expanded-cell-bg-color: transparent;
}

.table-container /deep/ .el-table__header thead th {
  font-weight: bold !important;
}
</style>
